
function getUserInfo () {
  $.ajax({
      url : 'login',
      method : 'get',
      success : function (body) {
        console.log(body)
          if (body.userId && body.userId > 0) {
              console.log('登录成功' + body.username)
              let preview = $('#preview')
            console.log(body)
              let src = 'userImage/' + body.imageUrl
              console.log(src)
              let img = $(`<img src=${src} alt="" class="via" id="image">`)
              preview.append(img)
              $('.blogger h3').text(body.username)
              $('#email').text(body.email)
              $('#age').text(body.age)
              $('#location').text(body.location)
              $('#profession').text(body.profession)
              $('#resume').text(body.resume)
              getUserData()
          } else {
              alert('用户尚未登录！请登录后重试。')
              location.assign('blog_login.html')
          }
      },
      error : function () {
          alert('用户尚未登录！请登录后重试。')
              location.assign('blog_login.html')
      }
  })
}

getUserInfo()

$('.btn').click(function editInfo() {
  value= $('.btn').val()
  console.log(value)
  if (value == "编辑信息") {
    console.log(1)
    var infoSpanMail = $('#email')
    var infoSpanAge = $('#age')
    var infoSpanLocation = $('#location')
    var infoSpanProfession = $('#profession')
    var infoSpanResume = $('#resume')
    var infoTextMail = infoSpanMail.text()
    var infoTextAge = infoSpanAge.text()
    var infoTextLocation = infoSpanLocation.text()
    var infoTextProfession = infoSpanProfession.text()
    var infoTextResume = infoSpanResume.text()

    let imageForm = $('<form></form>')
    imageForm.attr('action', "/QM_415/uploadServlet")
              .attr('method', 'post')
              .attr('id', 'postForm')
              .attr('enctype', 'multipart/form-data')
              .attr('onsubmit', 'return subfun()')
    let fileInput = $('<input>')
    let submitInput = $('<input>')
    fileInput.attr('type', 'file').attr('id', 'file-input').attr('name', 'file')
    submitInput.attr('type', 'submit').attr('id', 'upload-image').attr('value', '上传头像')
    imageForm.append(fileInput)
    imageForm.append(submitInput)
    console.log(imageForm)
    var inputMail = $('<input>').attr({
      'type': 'text',
      'value': infoTextMail
    }).attr('id', 'email').addClass('input-info')
    var inputAge = $('<select><option value="请选择">请选择</option></select>').attr('id', 'age').addClass('input-info')
    var inputLocation = $('<select><option value="请选择">请选择</option><option value="北京市">北京市</option><option value="天津市">天津市</option><option value="河北省">河北省</option><option value="山西省">山西省</option><option value="内蒙古自治区">内蒙古自治区</option><option value="辽宁省">辽宁省</option><option value="吉林省">吉林省</option><option value="黑龙江省">黑龙江省</option><option value="上海市">上海市</option><option value="江苏省">江苏省</option><option value="浙江省">浙江省</option><option value="安徽省">安徽省</option><option value="福建省">福建省</option><option value="江西省">江西省</option><option value="山东省">山东省</option><option value="河南省">河南省</option><option value="湖北省">湖北省</option><option value="湖南省">湖南省</option><option value="广东省">广东省</option><option value="广西壮族自治区">广西壮族自治区</option><option value="海南省">海南省</option><option value="重庆市">重庆市</option><option value="四川省">四川省</option><option value="贵州省">贵州省</option><option value="云南省">云南省</option><option value="西藏自治区">西藏自治区</option><option value="陕西省">陕西省</option><option value="甘肃省">甘肃省</option><option value="青海省">青海省</option><option value="宁夏回族自治区">宁夏回族自治区</option><option value="新疆维吾尔自治区">新疆维吾尔自治区</option><option value="台湾省">台湾省</option><option value="香港特别行政区">香港特别行政区</option><option value="澳门特别行政区">澳门特别行政区</option></select>').attr('id', 'location').addClass('input-info')
    var inputProfession = $('<select><option value="请选择">请选择</option><option value="前端开发工程师">前端开发工程师</option><option value="后端开发工程师">后端开发工程师</option><option value="UI设计师">UI设计师</option><option value="算法工程师">算法工程师</option><option value="学生">学生</option><option value="教师">教师</option></select>').attr('id', 'profession').addClass('input-info')
    var inputResume = $('<input>').attr({
      'type': 'text',
      'value': infoTextResume
    }).attr('id', 'resume').addClass('input-info')
    inputProfession.find('option').each(function() {
      if ($(this).attr('value') === infoTextProfession) {
        $(this).prop('selected', true);
      }
    })
    inputLocation.find('option').each(function() {
      if ($(this).attr('value') === infoTextLocation) {
        $(this).prop('selected', true);
      }
    })
    let head = $('#user-head')

    head.append(imageForm)

    console.log(imageForm)
    infoSpanMail.replaceWith(inputMail);
    infoSpanAge.replaceWith(inputAge)
    infoSpanLocation.replaceWith(inputLocation)
    infoSpanProfession.replaceWith(inputProfession)
    infoSpanResume.replaceWith(inputResume)

    var selectElement = document.getElementById("age");
    for (var i = 1; i <= 120; i++) {
      var optionElement = document.createElement("option");
      optionElement.value = i;
      optionElement.text = i;
      if (i == infoTextAge)
        optionElement.setAttribute('selected', 'selected')
      selectElement.appendChild(optionElement);
    }
    const fileIn = document.getElementById('file-input');
    const imagePreview = document.getElementById('image');

    fileIn.addEventListener('change', function() {
      const file = this.files[0];
      console.log(file)
      if (file) {
        const reader = new FileReader();
        reader.addEventListener('load', function() {
          console.log(this.result)
          imagePreview.setAttribute('src', this.result);
        });
        reader.readAsDataURL(file);
      }
    })

    $('.blogger').height('540px')
    var button = $('input[value="编辑信息"]')
    button.attr('value', '保存修改')
  } else {
    if ($('#age').val() == '请选择') {
      alert("请选择年龄！")
      return
    }
    if ($('#location').val() == '请选择') {
      alert("请选择地区！")
      return
    }
    if ($('#profession').val() == '请选择') {
      alert('请选择职位！')
      return
    }
    $.ajax({
      url : 'editInfo',
      method : 'post',
      data : {
        email : $('#email').val(),
        age : $('#age').val(),
        location : $('#location').val(),
        profession : $('#profession').val(),
        resume : $('#resume').val()
      },
      success : function(body) {
        console.log(body)
        if (body != "修改失败！") {
          console.log(2)
          var inputMail = $('#email')
          var inputAge = $('#age')
          var inputLocation = $('#location')
          var inputProfession = $('#profession')
          var inputResume = $('#resume')
          var infoTextMail = inputMail.val()
          var infoTextAge = inputAge.val()
          var infoTextLocation = inputLocation.val()
          var infoTextProfession = inputProfession.val()
          var infoTextResume = inputResume.val()
          console.log(3)
          var spanMail = $('<span></span>').attr('id', 'email').text(infoTextMail)
          var spanAge = $('<span></span>').attr('id', 'age').text(infoTextAge)
          var spanLocation = $('<span></span>').attr('id', 'location').text(infoTextLocation)
          var spanProfession = $('<span></span>').attr('id', 'profession').text(infoTextProfession)
          var spanResume = $('<span></span>').attr('id', 'resume').text(infoTextResume)
          inputMail.replaceWith(spanMail);
          inputAge.replaceWith(spanAge)
          inputLocation.replaceWith(spanLocation)
          inputProfession.replaceWith(spanProfession)
          inputResume.replaceWith(spanResume)
          $('#postForm').remove()
          $('#image').attr('src', 'userImage/' + body)
          console.log(body)
          var button = $('input[value="保存修改"]');
          button.attr('value', '编辑信息')
          $('.blogger').height('450px')
        } else {
          alert("修改失败！")
        }
      }
    })
  }
}
)
function subfun() {
  $.ajax({
    url : "/QM_415/uploadServlet",
    type : "post",
    data : new FormData($('#postForm')[0]),
    processData: false,
    contentType: false,
    success : function(data) {
      console.info(data);
      if (data == '上传成功！') alert('上传成功！')
      else if (data == '未上传头像！') alert('未上传头像！')
      else alert('上传失败！')
    },
    error : function(data) {
      console.log(data);
      alert('上传失败！')
    }
  });
  return false;
}

function getUserData() {
  $.ajax({
    url: 'data',
    method: 'get',
    success: function (body) {
      console.log(body)
      let visitCount = $('#visit-count')
      visitCount.text(body.visitCountByTotal)
      let blogCount = body.blogCountByTotal
      let categoryCount = body.categoryCountByTotal
      $('#blog-count').text(blogCount)
      $('#category-count').text(categoryCount)
      console.log(body)
      console.log(blogCount)
      console.log(categoryCount)
      if ($('#data-charts').length > 0) {
        chartForVisitByMonth(body)
        chartForVisitByAge(body)
        chartForBlogByMonth(body)
        chartForBlogByCategory(body)
        chartForVisitByProfession(body)
      }
    },
    error: function (body) {
      console.log(body)
      console.log('数据请求失败！')
    }
  })
}


function chartForVisitByMonth(body) {
  let curDiv = $('#visit-month-chart')
  if (Object.keys(body.visitCountByMonth).length === 0) {
    curDiv.replaceWith($('<div class="no-data">历史访问量：暂无数据</div>'))
    return
  }

  console.log(body.visitCountByMonth.length)
  let date = []
  let data = []
  for (var visitDate in body.visitCountByMonth) {
    date.push(visitDate)
    data.push(body.visitCountByMonth[visitDate])
  }

  var visitByMonthChartDom = document.getElementById('visit-month-chart');
  var visitByMonthChart = echarts.init(visitByMonthChartDom);
  var option;

  console.log(data)
  console.log(date)
  option = {
    tooltip: {
      trigger: 'axis',
      position: function (pt) {
        return [pt[0], '10%'];
      }
    },
    title: {
      left: 'center',
      text: '历史访问量',
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: date
    },
    yAxis: {
      type: 'value',
      boundaryGap: [0, '100%']
    },
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 10
      },
      {
        start: 0,
        end: 10
      }
    ],
    series: [
      {
        name: 'Fake Data',
        type: 'line',
        symbol: 'none',
        sampling: 'lttb',
        itemStyle: {
          color: 'rgb(255, 70, 131)'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgb(255, 158, 68)'
            },
            {
              offset: 1,
              color: 'rgb(255, 70, 131)'
            }
          ])
        },
        data: data
      }
    ]
  };

  option && visitByMonthChart.setOption(option);
}

function chartForBlogByMonth(body) {
  if (Object.keys(body.blogCountByMonth).length === 0) {
    $('#blog-month-chart').replaceWith($('<div class="no-data">发文数量：暂无数据</div>'))
    return
  }
  console.log(body.blogCountByMonth)
  let dict = body.blogCountByMonth
  let sortedDict = {};
  Object.keys(dict).sort(function(a, b) {
    // Split the keys into two parts based on the hyphen separator
    var aParts = a.split("-");
    var bParts = b.split("-");
    // Convert the two parts to numbers
    var aNum1 = parseInt(aParts[0]);
    var aNum2 = parseInt(aParts[1]);
    var bNum1 = parseInt(bParts[0]);
    var bNum2 = parseInt(bParts[1]);
    // Compare the two parts of the keys
    if (aNum1 < bNum1) {
      return -1;
    } else if (aNum1 > bNum1) {
      return 1;
    } else {
      if (aNum2 < bNum2) {
        return -1;
      } else if (aNum2 > bNum2) {
        return 1;
      } else {
        return 0;
      }
    }
  }).forEach(function(key) {
    sortedDict[key] = dict[key];
  });
  console.log(sortedDict)
  let blogMonthDate = []
  let blogMonthData = []
  for (var blogMonth in sortedDict) {
    blogMonthDate.push(blogMonth)
    blogMonthData.push(sortedDict[blogMonth])
  }
  var chartDom = document.getElementById('blog-month-chart');
  var blogByMonthChart = echarts.init(chartDom);
  var option;

  option = {
    title: {
      left: 'left',
      text: '发文数量',
    },
    tooltip: {
      show:true
    },
    xAxis: {
      type: 'category',
      data: blogMonthDate
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: blogMonthData,
        type: 'bar'
      }
    ]
  };

  option && blogByMonthChart.setOption(option);
}


function chartForVisitByAge(body) {
  if (Object.keys(body.visitCountByAge).length === 0) {
    $('#visit-age-chart').replaceWith($('<div class="no-data">访客分类：暂无数据</div>'))
    return
  }
  let visitByAgeData = []
  let countBelow18 = 0
  let count19_35 = 0
  let count36_60 = 0
  let countAbove60 = 0
  for (var age in body.visitCountByAge) {
    if (parseInt(age) >= 0 && parseInt(age) <= 18) countBelow18 = countBelow18 + 1;
    else if (parseInt(age) <= 35) count19_35 = count19_35 + 1;
    else if (parseInt(age) <= 60) count36_60 = count36_60 + 1;
    else countAbove60 = countAbove60 + 1;
  }
  curBelow18 = {}
  cur19_35 = {}
  cur36_60 = {}
  curAbove60 = {}
  curBelow18['name'] = '<= 18'
  curBelow18['value'] = countBelow18
  cur19_35['name'] = '19-35'
  cur19_35['value'] = count19_35
  cur36_60['name'] = '36-60'
  cur36_60['value'] = count36_60
  curAbove60['name'] = '>60'
  curAbove60['value'] = countAbove60
  visitByAgeData.push(curBelow18)
  visitByAgeData.push(cur19_35)
  visitByAgeData.push(cur36_60)
  visitByAgeData.push(curAbove60)
  console.log(visitByAgeData)
  var chartDom = document.getElementById('visit-age-chart');
  var visitByAgeChart = echarts.init(chartDom);
  var option;

  option = {
    title: {
      text: '访客分类',
      left: 'left'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: 'Access From',
        type: 'pie',
        radius: '50%',
        data: visitByAgeData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };

  option && visitByAgeChart.setOption(option);
}

function chartForVisitByProfession(body) {
  if (Object.keys(body.visitCountByProfession).length === 0) {
    $('#visit-profession-chart').replaceWith($('<div class="no-data">访客背景：暂无数据</div>'))
    return
  }
  let visitByProfessionData = []
  let devideData = []
  let maxv = 0
  for (var profession in body.visitCountByProfession) if (parseInt(body.visitCountByProfession[profession]) > maxv) maxv = parseInt(body.visitCountByProfession[profession])
  for (var profession in body.visitCountByProfession) {
    let curData = {}
    curData['name'] = profession
    curData['max'] = maxv
    devideData.push(body.visitCountByProfession[profession])
    visitByProfessionData.push(curData)
  }
  console.log(visitByProfessionData)
  var chartDom = document.getElementById('visit-profession-chart');
  var visitByProfessionChart = echarts.init(chartDom);
  var option;

  option = {
    title: {
      text: '访客背景'
    },
    tooltip: {
      show: true
    },
    radar: {
      // shape: 'circle',
      indicator: visitByProfessionData
    },
    series: [
      {
        name: 'visitor',
        type: 'radar',
        data: [
          {
            value: devideData,
            name: 'Allocated Budget'
          }
        ]
      }
    ]
  };

  option && visitByProfessionChart.setOption(option);
}


function chartForBlogByCategory(body) {
  if (Object.keys(body.categoryCountByDevide).length === 0) {
    $('#blog-category-chart').replaceWith($('<div class="no-data">博文类别：暂无数据</div>'))
    return
  }
  let blogByCategoryData = []
  console.log(body)
  for (var category in body.categoryCountByDevide) {
    console.log(category)
    let curData = {}
    curData['name'] = category
    curData['value'] = body.categoryCountByDevide[category]
    blogByCategoryData.push(curData)
  }
  console.log(blogByCategoryData)
  var chartDom = document.getElementById('blog-category-chart');
  var blogByCategoryChart = echarts.init(chartDom);
  var option;

  option = {
    title: {
      text: '博文类别'
    },
    tooltip: {
      show: true,
      formatter: function (a) {
        return a.name + '\n\n' + a.value + ' 篇';
      }
    },
    series: [

      {
        type: 'treemap',
        data: blogByCategoryData
      }
    ]
  };

  option && blogByCategoryChart.setOption(option);
}


